<template>
	<view class="tenant-key">
		<view class="key-header">
			<view class="header-title">住户钥匙管理</view>
		</view>
		
	
		
		<scroll-view class="key-list" scroll-y @scrolltolower="loadMore">
			<block v-if="loading && keyList.length === 0">
				<view class="loading">加载中...</view>
			</block>
			
			<block v-else-if="keyList.length === 0">
				<view class="empty-data">
					<image src="/static/images/empty.png" mode="aspectFit"></image>
					<text>暂无钥匙数据</text>
				</view>
			</block>
			
			<block v-else>
				<view 
					class="key-item" 
					v-for="(item, index) in keyList" 
					:key="item.id || index"
				>
					<view class="key-info">
						<!-- MAC地址 -->
						<!-- <view class="key-mac">
							<text class="info-label">MAC:</text>
							<text class="info-value">{{ item.mac || '未设置' }}</text>
						</view> -->
						
						<!-- 地址信息 -->
						<!-- <view class="key-address">
							<text class="info-label">地址:</text>
							<text class="info-value">{{ item.cellName }} {{ item.unitName }} {{ item.floorName }} {{ item.roomName }}</text>
						</view> -->
						
						<!-- 租户信息 -->
						<view class="key-tenant">
							<text class="info-label">姓名:</text>
							<text class="info-value">{{ item.tenantName }} ({{ item.phone }})</text>
						</view>
						
						<!-- 身份证号 -->
						<view class="key-idcard">
							<text class="info-label">学工号:</text>
							<text class="info-value">{{ item.idCardNumber }}</text>
						</view>
						
						<!-- 住户信息 -->
				<!-- 		<view class="key-user">
							<text class="info-label">住户:</text>
							<text class="info-value">{{ item.userName }} ({{ item.userPhone }})</text>
						</view> -->
						
						<!-- 关系 -->
						<view class="key-relation">
							<text class="info-label">关系:</text>
							<text class="info-value">{{ formatRelation(item.relation) }}</text>
						</view>
						
						<!-- 钥匙类型 -->
						<view class="key-type">
							<text class="info-label">类型:</text>
							<text class="info-value">{{ formatKeyType(item.type) }}</text>
						</view>
						
						<!-- 密码 -->
						<view class="key-password">
							<text class="info-label">密码:</text>
							<text class="info-value">{{ item.password || '未设置' }}</text>
						</view>
						
						<!-- 有效期 -->
						<view class="key-validity">
							<text class="info-label">有效期:</text>
							<text class="info-value">{{ formatDate(item.startTime) }} 至 {{ formatDate(item.endTime) }}</text>
						</view>
						
						<!-- 状态信息 -->
						<view class="key-status">
							<view class="status-item">
								<text class="info-label">生效状态:</text>
								<text class="info-value" :class="[item.status === 1 ? 'status-active' : 'status-inactive']">
									{{ item.status === 1 ? '已生效' : '未生效' }}
								</text>
							</view>
							<view class="status-item">
								<text class="info-label">冻结状态:</text>
								<text class="info-value" :class="[item.isItAvailable === 1 ? 'status-frozen' : 'status-normal']">
									{{ item.isItAvailable === 1 ? '已冻结' : '正常' }}
								</text>
							</view>
					<!-- 		<view class="status-item">
								<text class="info-label">授权状态:</text>
								<text class="info-value" :class="[item.isKeyRz === '1' ? 'status-active' : 'status-inactive']">
									{{ item.isKeyRz === '1' ? '已授权' : '未授权' }}
								</text>
							</view> -->
						</view>
						
						<!-- 备注 -->
						<view class="key-remark" v-if="item.remark">
							<text class="info-label">备注:</text>
							<text class="info-value">{{ item.remark }}</text>
						</view>
					</view>
				</view>
			</block>
		</scroll-view>
	</view>
</template>

<script>
	import { listTenantkey, getKey, delKey, addKey, updateKey } from '@/api/lock/tenantKeys';
	
	export default {
		name: 'TenantKey',
		props: {
			roomId: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				// 列表数据
				keyList: [],
				loading: false,
				pageNum: 1,
				pageSize: 20,
				hasMore: true,
				// 表单参数
				form: {
					id: null,
					username: '',
					userPhone: '',
					keyType: '',
					relation: '',
					beginTime: '',
					endTime: '',
					roomId: ''
				},
				// 表单标题
				formTitle: '添加钥匙',
				// 是否编辑模式
				isEdit: false,
				// 钥匙类型选项
				keyTypeOptions: [
					{ value: '1', label: '密码' },
					{ value: '2', label: '卡片' }
				],
				
				// 关系选项
				relationOptions: [
					{ value: '0', label: '本人' },
					{ value: '1', label: '父亲' },
					{ value: '2', label: '母亲' },
					{ value: '3', label: '儿子' },
					{ value: '4', label: '女儿' },
					{ value: '5', label: '其他' }
				],
				// 当前选中的钥匙类型索引
				keyTypeIndex: 0,
				// 当前选中的关系索引
				relationIndex: 0
			}
		},
		watch: {
			// 监听 roomId 变化，重新加载数据
			roomId: {
				handler(newVal) {
					if (newVal) {
						console.log('TenantKey组件收到新的roomId:', newVal);
						this.pageNum = 1;
						this.hasMore = true;
						this.keyList = [];
						this.getKeyList();
					}
				},
				immediate: true
			}
		},
		created() {
			// 移除这里的getKeyList调用，改为在watch中处理
			console.log('TenantKey组件创建，roomId:', this.roomId);
		},
		methods: {
			// 获取钥匙列表
			getKeyList() {
				if (this.loading) return;
				
				this.loading = true;
				console.log('开始获取钥匙列表，参数:', {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					homeId: this.roomId
				});
				
				// 确保homeId存在
				if (!this.roomId) {
					console.warn('roomId不存在，无法获取数据');
					this.loading = false;
					return;
				}
				
				const params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					homeId: this.roomId
				};
				
				listTenantkey(params)
					.then(response => {
						console.log('获取钥匙列表响应:', response);
						
						if (response.code === 200) {
							const newList = response.rows || [];
							console.log('新数据列表:', newList);
							
							if (this.pageNum === 1) {
								this.keyList = newList;
							} else {
								this.keyList = [...this.keyList, ...newList];
							}
							
							this.hasMore = newList.length === this.pageSize;
							console.log('更新后的keyList:', this.keyList);
							
							// 数据加载完成后，强制更新视图
							this.$forceUpdate();
						} else {
							throw new Error(response.msg || '获取数据失败');
						}
					})
					.catch(error => {
						console.error('获取钥匙列表错误:', error);
						uni.showToast({
							title: error.message || '获取钥匙列表失败',
							icon: 'none'
						});
					})
					.finally(() => {
						this.loading = false;
						uni.stopPullDownRefresh();
					});
			},
			
			// 加载更多
			loadMore() {
				if (!this.loading && this.hasMore) {
					this.pageNum++;
					this.getKeyList();
				}
			},
			
			// 重置并刷新
			refresh() {
				this.pageNum = 1;
				this.hasMore = true;
				this.getKeyList();
			},
			
			// 格式化钥匙类型
			formatKeyType(type) {
				const typeMap = {
					'1': '密码',
					'2': '卡片'
				};
				return typeMap[type] || '未知类型';
			},
			
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '未设置';
				return dateStr.split(' ')[0]; // 只显示日期部分
			},
			
			// 打开添加钥匙表单
			handleAddKey() {
				this.resetForm();
				this.isEdit = false;
				this.formTitle = '添加钥匙';
				this.form.roomId = this.roomId;
				this.$refs.keyFormPopup.open();
			},
			
			// 打开编辑钥匙表单
			handleEditKey(item) {
				this.resetForm();
				this.isEdit = true;
				this.formTitle = '编辑钥匙';
				
				// 填充表单数据
				this.form.id = item.id;
				this.form.username = item.username;
				this.form.userPhone = item.userPhone;
				this.form.keyType = item.keyType;
				this.form.relation = item.relation;
				this.form.beginTime = item.beginTime ? item.beginTime.split(' ')[0] : '';
				this.form.endTime = item.endTime ? item.endTime.split(' ')[0] : '';
				this.form.roomId = this.roomId;
				
				// 设置选择器索引
				this.keyTypeIndex = this.keyTypeOptions.findIndex(option => option.value == item.keyType);
				this.relationIndex = this.relationOptions.findIndex(option => option.value == item.relation);
				
				if (this.keyTypeIndex === -1) this.keyTypeIndex = 0;
				if (this.relationIndex === -1) this.relationIndex = 0;
				
				this.$refs.keyFormPopup.open();
			},
			
			// 删除钥匙
			handleDeleteKey(item) {
				uni.showModal({
					title: '提示',
					content: '确定要删除此钥匙吗？',
					success: res => {
						if (res.confirm) {
							delKey(item.id).then(response => {
								if (response.code === 200) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
									this.getKeyList();
								} else {
									uni.showToast({
										title: response.msg || '删除失败',
										icon: 'none'
									});
								}
							});
						}
					}
				});
			},
			
			// 关闭表单
			closeForm() {
				this.$refs.keyFormPopup.close();
			},
			
			// 重置表单
			resetForm() {
				this.form = {
					id: null,
					username: '',
					userPhone: '',
					keyType: '1',
					relation: '1',
					beginTime: '',
					endTime: '',
					roomId: this.roomId
				};
				this.keyTypeIndex = 0;
				this.relationIndex = 0;
			},
			
			// 钥匙类型变化
			handleKeyTypeChange(e) {
				this.keyTypeIndex = e.detail.value;
				this.form.keyType = this.keyTypeOptions[this.keyTypeIndex].value;
			},
			
			// 关系变化
			handleRelationChange(e) {
				this.relationIndex = e.detail.value;
				this.form.relation = this.relationOptions[this.relationIndex].value;
			},
			
			// 开始时间变化
			onBeginTimeChange(e) {
				this.form.beginTime = e.detail.value;
			},
			
			// 结束时间变化
			onEndTimeChange(e) {
				this.form.endTime = e.detail.value;
			},
			
			// 表单提交
			submitForm() {
				// 表单验证
				if (!this.form.username) {
					uni.showToast({
						title: '请输入用户名',
						icon: 'none'
					});
					return;
				}
				
				if (!this.form.userPhone) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
					return;
				}
				
				if (!/^1\d{10}$/.test(this.form.userPhone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}
				
				if (!this.form.beginTime) {
					uni.showToast({
						title: '请选择开始时间',
						icon: 'none'
					});
					return;
				}
				
				if (!this.form.endTime) {
					uni.showToast({
						title: '请选择结束时间',
						icon: 'none'
					});
					return;
				}
				
				// 格式化时间
				this.form.beginTime = `${this.form.beginTime} 00:00:00`;
				this.form.endTime = `${this.form.endTime} 23:59:59`;
				
				const submitForm = { ...this.form };
				
				uni.showLoading({
					title: '保存中...'
				});
				
				if (this.isEdit) {
					// 更新钥匙
					updateKey(submitForm).then(response => {
						if (response.code === 200) {
							uni.showToast({
								title: '修改成功',
								icon: 'success'
							});
							this.closeForm();
							this.getKeyList();
						} else {
							uni.showToast({
								title: response.msg || '修改失败',
								icon: 'none'
							});
						}
						uni.hideLoading();
					}).catch(() => {
						uni.hideLoading();
						uni.showToast({
							title: '修改失败',
							icon: 'none'
						});
					});
				} else {
					// 添加钥匙
					addKey(submitForm).then(response => {
						if (response.code === 200) {
							uni.showToast({
								title: '添加成功',
								icon: 'success'
							});
							this.closeForm();
							this.getKeyList();
						} else {
							uni.showToast({
								title: response.msg || '添加失败',
								icon: 'none'
							});
						}
						uni.hideLoading();
					}).catch(() => {
						uni.hideLoading();
						uni.showToast({
							title: '添加失败',
							icon: 'none'
						});
					});
				}
			},
			
			// 格式化关系
			formatRelation(relation) {
				const relationMap = {
					'0': '本人',
					'1': '父亲',
					'2': '母亲',
					'3': '儿子',
					'4': '女儿',
					'5': '其他'
				};
				return relationMap[relation] || '未知';
			}
		}
	}
</script>

<style>
	.tenant-key {
		min-height: 100vh;
		background-color: #f6f8fa;
		padding: 24rpx;
	}
	
	.key-header {
		background-color: #fff;
		padding: 32rpx;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
	}
	
	.header-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #2c3e50;
		position: relative;
		padding-left: 24rpx;
	}
	
	.header-title::before {
		content: '';
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 6rpx;
		height: 32rpx;
		background: linear-gradient(to bottom, #409eff, #67c23a);
		border-radius: 6rpx;
	}
	
	.key-list {
		padding-bottom: 40rpx;
	}
	
	.loading {
		text-align: center;
		padding: 40rpx;
		color: #909399;
		font-size: 28rpx;
	}
	
	.empty-data {
		padding: 120rpx 0;
		text-align: center;
	}
	
	.empty-data image {
		width: 240rpx;
		height: 240rpx;
		margin-bottom: 24rpx;
	}
	
	.empty-data text {
		font-size: 28rpx;
		color: #909399;
	}
	
	.key-item {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		padding: 32rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
	}
	
	.key-item:active {
		transform: scale(0.99);
	}
	
	.key-info {
		position: relative;
	}
	
	.key-tenant,
	.key-idcard,
	.key-user,
	.key-relation,
	.key-type,
	.key-password,
	.key-validity {
		margin-bottom: 24rpx;
		display: flex;
		align-items: center;
		padding: 16rpx;
		background-color: #f8fafc;
		border-radius: 12rpx;
		transition: all 0.3s ease;
	}
	
	.key-tenant:hover,
	.key-idcard:hover,
	.key-user:hover,
	.key-relation:hover,
	.key-type:hover,
	.key-password:hover,
	.key-validity:hover {
		background-color: #f0f2f5;
	}
	
	.info-label {
		color: #606266;
		font-size: 28rpx;
		min-width: 140rpx;
		font-weight: 500;
	}
	
	.info-value {
		color: #2c3e50;
		font-size: 28rpx;
		flex: 1;
		padding-left: 16rpx;
	}
	
	.key-status {
		margin-top: 32rpx;
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		padding: 24rpx;
		background: #f8fafc;
		border-radius: 12rpx;
	}
	
	.status-item {
		background-color: #fff;
		padding: 12rpx 24rpx;
		border-radius: 30rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}
	
	.status-item .info-label {
		font-size: 26rpx;
		min-width: auto;
		margin-right: 12rpx;
	}
	
	.status-item .info-value {
		font-size: 26rpx;
		padding-left: 0;
	}
	
	.status-active {
		color: #67c23a;
		font-weight: 500;
	}
	
	.status-inactive {
		color: #909399;
	}
	
	.status-frozen {
		color: #e6a23c;
		font-weight: 500;
	}
	
	.status-normal {
		color: #67c23a;
		font-weight: 500;
	}
	
	.key-remark {
		margin-top: 24rpx;
		padding: 24rpx;
		background-color: #fff7ed;
		border-radius: 12rpx;
		border: 1px dashed #f5a623;
	}
	
	.key-remark .info-label {
		color: #f5a623;
	}
	
	.key-remark .info-value {
		color: #875a1b;
	}
	
	/* 添加动画效果 */
	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
	
	.key-item {
		animation: fadeIn 0.3s ease-out;
	}
	
	/* 添加滚动条样式 */
	::-webkit-scrollbar {
		width: 8rpx;
		background-color: transparent;
	}
	
	::-webkit-scrollbar-thumb {
		background-color: #e0e3e9;
		border-radius: 4rpx;
	}
	
	::-webkit-scrollbar-track {
		background-color: transparent;
	}
</style>
  